package com.atzzy.ysmall.ysmall_orderserviceimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atzzy.ysmall.ysmall_allService.orderService.OrderService;
import com.atzzy.ysmall.ysmall_beans.*;
import com.atzzy.ysmall.ysmall_common.utils.PageHelper;
import com.atzzy.ysmall.ysmall_common.vo.R;
import com.atzzy.ysmall.ysmall_mapper.OrderItemMapper;
import com.atzzy.ysmall.ysmall_mapper.OrdersMapper;
import com.atzzy.ysmall.ysmall_mapper.ProductSkuMapper;
import com.atzzy.ysmall.ysmall_mapper.ShoppingsCartMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

/**
 * @Author JAVAZeng
 * @Date 2022/4/5 22:01
 * @Version 1.0
 */
@Service
@Component
public class OrdersServiceImpl implements OrderService
{
    @Resource
    private ShoppingsCartMapper shoppingCartMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private ProductSkuMapper productSkuMapper;
    @Override
    @Transactional
    public Map<String,String> addOrder(String cids, Orders orders) throws SQLException{
        Map<String,String> map = new HashMap<>();
        //根据cids查询当前订单中关联得购物车记录详情
        String[] arr = cids.split(",");
        List<Integer> cidsList = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            cidsList.add(Integer.parseInt(arr[i]));
        }
        List<ShoppingCartVo> sCs = shoppingCartMapper.selectShopCartByCids(cidsList);


        //校验库存
        boolean f = true;
        String untitled = "";
        for (ShoppingCartVo sc : sCs) {
            if (Integer.parseInt(sc.getCartNum()) > sc.getSkuStock()) {
                f = false;
                break;
            }

            //获取所有商品的名字 以，分割 拼接成字符串
            untitled = untitled + sc.getProductName() + ",";
        }
        if (f) {
            //表示库存充足-----保存订单
            //userId
            //untitled
            //收货人信息 姓名  电话  地址
            //总价格
            //支付方式
            //叮当创建时间
            //订单初始状态
            orders.setUntitled(untitled);
            orders.setCreateTime(new Date());
            orders.setStatus("1");
            //生成订单Id
            String orderId = UUID.randomUUID().toString().replace("-", "");
            orders.setOrderId(orderId);
            int i = ordersMapper.insertOrder(orders);//保存订单
            if (i > 0) {
                //生成商品快照
                List<OrderItem> orderItems = new ArrayList<>();
                for (ShoppingCartVo sc : sCs) {
                    String itemId = System.currentTimeMillis() + "" + (new Random().nextInt(89999) + 10000);
                    int cnum = Integer.parseInt(sc.getCartNum());
                    OrderItem orderItem = new OrderItem(itemId, orderId, sc.getProductId(), sc.getProductName(), sc.getUrl(), sc.getSkuId(), sc.getSkuName(), sc.getSellPrice(), cnum, sc.getSellPrice() * cnum, new Date(), new Date(), 0);
                    orderItems.add(orderItem);
                }
                int j = orderItemMapper.insertList(orderItems);

                for(ShoppingCartVo sc: sCs)
                {
                    String skuId = sc.getSkuId();
                    int stock = sc.getSkuStock()-Integer.parseInt(sc.getCartNum());

                    productSkuMapper.updateProductSkuNum(skuId,stock);
                }
                //5.扣减库存
                // 商品1 奥利奥小兵干

                //删除购物车
                for(int cid: cidsList)
                {
                    shoppingCartMapper.deleteCartByCarId(cid);
                }
            }
            map.put("orderId",orderId);
            map.put("productNames",untitled);
            return map;
        } else {
            //表示库存不足
            return null;
        }
    }

    @Override
    public int updateOrderStatus(String orderId, String status) {
        int updateStatus = ordersMapper.updateStatus(orderId, status);
        return updateStatus;
    }

    @Override
    public R getOrderById(String orderId) {
        Orders orders = ordersMapper.getOrderById(orderId);

        return new R(201,"success",orders.getStatus());
    }

    @Override
    public R listOrders(String userId, String status, int pageNum, int limit) {
        int pageCount = 0;
        int start = (pageNum-1)*limit;
        List<OrdersVo> ordersVos = ordersMapper.selectOrders(userId, status, start, limit);
        if(status !=null &&  !"".equals(status))
        {
            int count = ordersMapper.selectCountByStatusAndUserId(userId, status);
            pageCount = count%limit==0? count/limit:count/limit+1;
            PageHelper<OrdersVo> ordersVoPageHelper = new PageHelper<>(count, pageCount, ordersVos);
            return new R(201,"success",ordersVoPageHelper);
        }else {
            int count2 = ordersMapper.selectCountByUserId(userId);
            pageCount = count2%limit==0? count2/limit:count2/limit+1;
            PageHelper<OrdersVo> ordersVoPageHelper2 = new PageHelper<>(count2, pageCount, ordersVos);
            return new R(201,"success",ordersVoPageHelper2);
        }
    }
}
